#include <iostream>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

void ChildWrite(int wfd)
{
    char buff[1024];
    int cnt = 0;
    while(1)
    {
        snprintf(buff, sizeof(buff), "i am child, pid:%d, cnt:%d", getpid(), cnt++);
        write(wfd, buff, strlen(buff));
        sleep(1);
    }
}

void FatherRead(int rfd)
{
    char buff[1024];
    while(1)
    {
        buff[0] = 0;
        ssize_t n = read(rfd, buff, sizeof(buff)-1);
        if(n > 0)
        {
            buff[n] = 0;
            cout << "child say: " << buff << endl;
        }
    }
}

int main()
{
    //创建管道
    int fds[2] = {0};//0读1写
    int n = pipe(fds);
    if(n < 0)
    {
        cout << "error" << endl;
    }
    cout << "fd[0]:" << fds[0] << " fd[1]:"<<fds[1] << endl;
    
    //创建子进程
    pid_t id = fork();
    if(id == 0)
    {
        close(fds[0]);
        ChildWrite(fds[1]);
        close(fds[1]);
        exit(0);
    }
    //关闭不需要的读写端, 形成通信信道
    //f->r, c->w
    close(fds[1]);
    FatherRead(fds[0]);

    waitpid(id, nullptr, 0);

    close(fds[0]);
    return 0;
}
